<template>
  <a-drawer
    :maskClosable="false"
    :title="title"
    :width="width"
    :visible="visible"
    @close="handleCancel">

    <a-form-model ref="form" :model="model" layout="vertical" :rules="validatorRules">

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="申请人">
            <SelectUserByDep placeholder="请选择申请人" v-model="model.proposer" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="申请部门">
            <j-select-depart placeholder="请选择申请部门" v-model="model.proposerDeptId" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="申请时间">
            <j-date
              placeholder="请选择申请时间"
              v-model="model.createTime"
              :show-time="true"
              date-format="YYYY-MM-DD HH:mm"
              style="width: 100%"
              disabled/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-divider>往来单位信息</a-divider>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="企业名称" prop="enterpriseName">
            <a-input v-model="model.enterpriseName" placeholder="请输入企业名称" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="企业信用代码" prop="enterpriseCreditCode">
            <a-input v-model="model.enterpriseCreditCode" placeholder="请输入企业信用代码" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="企业地址" prop="enterpriseAddress">
            <a-input :max-length="100" v-model="model.enterpriseAddress" placeholder="请输入企业地址" ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="收款账户名称" prop="bankAccountName">
            <a-input v-model="model.bankAccountName" placeholder="请输入收款账户名称" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="开户行联行号" prop="cnapsCode">
            <SelectFinanceKingdeeBankInput v-model="model.cnapsCode" placeholder="请选择联行号" @back="backCnapsCode" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="开户行" prop="bankName">
            <a-input v-model="model.bankName" placeholder="请输入开户行" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="银行账号" prop="bankAccountNo">
            <a-input v-model="model.bankAccountNo" placeholder="请输入银行账号" :max-length="32"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="合作业务" prop="mainBussiness">
            <a-textarea :max-length="500" v-model="model.mainBussiness" rows="4" placeholder="请输入合作业务" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider>联系人信息</a-divider>
      <erp-purchase-supplier-contact-list ref="contactList"></erp-purchase-supplier-contact-list>

    </a-form-model>

    <div class="drawer-footer">
      <a-button @click="saveSubTo" type="primary" :loading="loading" style="margin-right: 20px;">提交</a-button>
      <a-popconfirm title="确定关闭弹窗吗?" @confirm="handleCancel" :getPopupContainer="(node) => node.parentNode">
        <a-button style="margin-bottom: 0;">关闭</a-button>
      </a-popconfirm>
    </div>

  </a-drawer>
</template>

  <script>
  import { getAction, postAction, putAction } from '@api/manage'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectFinanceKingdeeBankInput from '@/views/scy/components/SelectFinanceKingdeeBankInput'
  import { mapGetters } from 'vuex'
  import moment from 'moment'
  import ErpPurchaseSupplierContactList from '@/views/erp/purchase/supplier/modules/reference/ErpPurchaseSupplierContactList'; // 联系人信息
  let addSupplier = '/api/erp/purchase/supplier/erpPurchaseSupplier/addSupplier'
  let queryByEnterpriseName = '/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseName'
  let queryByEnterpriseCreditCode = '/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseCreditCode'
  let editSupplier = '/api/erp/purchase/supplier/erpPurchaseSupplier/editSupplier'

  export default {
      name: 'UnSupplierForm',
      components: {
        SelectUserByDep,
        SelectFinanceKingdeeBankInput,
        ErpPurchaseSupplierContactList
        },
      data () {
        return {
          title: '',
          width: 800,
          validatorRules: {
            enterpriseName: [
              { required: true, message: '请输入企业名称!' },
              { validator: this.validatorEnterpriseName, trigger: 'blur' }
            ],
            enterpriseCreditCode: [
              { required: true, message: '请输入企业信用代码!' },
              { validator: this.validatorEnterpriseCreditCode, trigger: 'blur' }
            ],
            bankAccountName: [
              { required: true, message: '请输入收款账户名称!' }
            ],
            cnapsCode: [
              { required: true, message: '请选择开户行联行号!' }
            ],
            bankName: [
              { required: true, message: '请输入开户行!' }
            ],
            bankAccountNo: [
              { required: true, message: '请输入银行账号!' }
            ],
            mainBussiness: [
              { required: true, message: '请输入合作业务!', trigger: 'blur' }
            ],
            enterpriseAddress: [
              { required: true, message: '请输入企业地址!', trigger: 'blur' }
            ]
          },
          model: {
            proposer: '',
            proposerDeptId: '',
            createTime: '',
            enterpriseName: '',
            bankAccountName: '',
            enterpriseCreditCode: '',
            enterpriseAddress: '',
            mainBussiness: '',
            bankName: '',
            bankAccountNo: '',
            cnapsCode: ''
          },
          id: '',
          visible: false,
          loading: false,
          bankAccountName: '',
          enterpriseCreditCode: '',
          enterpriseAddress: '',
          mainBussiness: '',
          enterpriseName: '',
          cnapsCode: ''
        }
      },
      methods: {
        ...mapGetters(['userInfo']),
        backCnapsCode(data) {
          if (data) {
            this.$set(this.model, 'bankName', data[0].bankBranchName)
          }
        },
        async validatorEnterpriseName (rule, value, callback) {
            let id = 1;
            if (this.id) {
                id = this.id
            }
            let res = await getAction(queryByEnterpriseName, { enterpriseName: value, commercialType: '2', id: id })
            if (res.success) {
                if (res.result == '0') {
                    callback()
                } else {
                    this.enterpriseName == value ? callback() : callback('企业名称已存在，请重新输入！')
                }
                } else {
                    this.$message.warning(res.message)
                }
        },
        async validatorEnterpriseCreditCode(rule, value, callback) {
            let res = await getAction(queryByEnterpriseCreditCode, { enterpriseCreditCode: value, commercialType: '2' })

                if (res.success) {
                    if (res.result == '0') {
                        callback()
                    } else {
                        this.enterpriseCreditCode == value ? callback() : callback('企业信用代码已存在，请重新输入！')
                    }
                } else {
                    this.$message.warning(res.message)
                }
        },
        async getInitData(record) {
            this.visible = true
            this.title = record ? '编辑' : '新增'
            if (record) {
                for (const key in record) {
                    if (Object.hasOwnProperty.call(this.model, key)) {
                        this.model[key] = record[key]
                    }
                }

                this.id = record.id
                this.enterpriseName = record.enterpriseName
                this.bankAccountName = record.bankAccountName
                this.cnapsCode = record.cnapsCode
                this.enterpriseCreditCode = record.enterpriseCreditCode
                this.model.proposer = this.userInfo().empId; // 当前登录人
                this.model.proposerDeptId = this.userInfo().deptId; // 当前登录人部门
                this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
                this.$nextTick(() => {
                   if (record.id) {
                    this.$refs.contactList.loadData(1, record.id)
                  } else {
                    this.$refs.contactList.dataSource = []
                  }
                })
            } else {
                this.id = ''
                this.model.proposer = this.userInfo().empId; // 当前登录人
                this.model.proposerDeptId = this.userInfo().deptId; // 当前登录人部门
                this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
                this.enterpriseName = ''
                this.enterpriseCreditCode = ''
                this.bankAccountName = ''
                this.cnapsCode = ''
                this.$refs.contactList.dataSource = []
            }
        },
        // 提交或者保存
        saveSubTo() {
          let details = this.$refs.contactList.submitForm()
            if (!details.length > 0) {
              this.$message.warning('请添加联系人信息！');
              this.$emit('unButtonDisable');
              return
            }
            this.$refs.form.validate(async rr => {
                if (rr) {
                    this.loading = true
                    let params = {
                        commercialType: '2',
                        proposerText: this.userInfo().realname,
                        proposerDeptIdText: this.userInfo().orgCodeTxt,
                        ...this.model,
                        detailList: details
                    }

                    let res = this.id ? await putAction(editSupplier, {
                        ...params,
                        id: this.id
                    }) : await postAction(addSupplier, params)

                    if (res.success) {
                        this.handleCancel()
                        this.$emit('ok')

                        this.$message.success('操作成功!')
                    } else {
                        this.loading = false
                    }
                } else {
                    // this.$message.error('请填写必要数据!')
                }
            })
        },
        handleCancel() {
            this.visible = false
            this.loading = false
            this.$refs.form.resetFields()
            this.model = {
                proposer: '',
                proposerDeptId: '',
                createTime: '',
                enterpriseName: '',
                bankAccountName: '',
                enterpriseCreditCode: '',
                enterpriseAddress: '',
                mainBussiness: '',
                bankName: '',
                bankAccountNo: '',
                cnapsCode: ''
            }
            this.id = ''
        }
      }
    }
  </script>
<style lang="less" scoped>
    .drawer-footer{
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
    z-index: 100;
  }
</style>
